<!--
 * @Author: your name
 * @Date: 2021-05-25 09:04:06
 * @LastEditTime: 2021-06-05 13:40:01
 * @LastEditors: Please set LastEditors
 * @Description: In User Settings Edit
 * @FilePath: \exam-web\src\views\_tchTest\index.vue
-->
<template>
  <div v-loading="isLoading" class="wrapper">
    <!-- 顶部导航栏 -->
    <div class="card">
      <div v-if="pageIndex === 0">
        <div class="flex-row">
          <el-button type="primary" @click="reloadPage">刷新页面</el-button>
          <p style="margin-left:10px">
            以下数据基于服务器时间<strong style="color:#eb3941">{{ homePage.serverTimeNow }}</strong>，添加数据后请刷新！
          </p>
          <div style="flex:1;" />
          <el-button type="primary" @click="goToAddExamPage">新增考试</el-button>
        </div>
      </div>
      <div v-if="pageIndex !== 0">
        <el-page-header :content="pageIndex" @back="goBack" />
      </div>
    </div>
    <!-- 首页 -->
    <div v-if="pageIndex === 0" class="card">
      <el-tabs v-model="homePage.tabsActiveName">
        <el-tab-pane label="进行中" name="0">

          <el-table :data="homePage.haveBegunTableData" border style="width: 100%;">
            <el-table-column v-for="item in homePage.tableHead" :key="item.prop" :prop="item.prop" :label="item.label" :width="item.width" />
            <el-table-column label="操作" width="192">
              <template slot-scope="{ row }">
                <el-button-group>
                  <el-button type="primary" icon="el-icon-view" @click="onGetRowInfo(row)" />
                  <el-button type="primary" icon="el-icon-edit" />
                  <el-button type="primary" icon="el-icon-delete" @click="beforeDeleteExamRow(row)" />
                </el-button-group>
              </template>
            </el-table-column>
          </el-table>

        </el-tab-pane>
        <el-tab-pane label="未开始" name="1">

          <el-table :data="homePage.notStartTableData" border style="width: 100%;">
            <el-table-column v-for="item in homePage.tableHead" :key="item.prop" :prop="item.prop" :label="item.label" :width="item.width" />
            <el-table-column label="操作" width="192">
              <template slot-scope="{ row }">
                <el-button-group>
                  <el-button type="primary" icon="el-icon-view" @click="onGetRowInfo(row)" />
                  <el-button type="primary" icon="el-icon-edit" />
                  <el-button type="primary" icon="el-icon-delete" @click="beforeDeleteExamRow(row)" />
                </el-button-group>
              </template>
            </el-table-column>
          </el-table>

        </el-tab-pane>
        <el-tab-pane label="已结束" name="2">

          <el-table :data="homePage.isOverTableData" border style="width: 100%;">
            <el-table-column v-for="item in homePage.tableHead" :key="item.prop" :prop="item.prop" :label="item.label" :width="item.width" />
            <el-table-column label="操作" width="192">
              <template slot-scope="{ row }">
                <el-button-group>
                  <el-button type="primary" icon="el-icon-view" @click="onGetRowInfo(row)" />
                  <el-button type="primary" icon="el-icon-edit" />
                  <el-button type="primary" icon="el-icon-delete" @click="beforeDeleteExamRow(row)" />
                </el-button-group>
              </template>
            </el-table-column>
          </el-table>

        </el-tab-pane>
      </el-tabs>
    </div>
    <!-- 跳转页 -->
    <div v-if="pageIndex === 1" class="narrow-card">
      啊
    </div>
    <!-- 新增考试 -->
    <div v-if="pageIndex === '新增考试'" class="narrow-card">
      <el-row>
        <el-col :span="12">
          <div>
            <p>
              考试名称
            </p>
            <p>
              <el-input v-model="addExam.e_name" class="input-width" maxlength="16" placeholder="请输入考试名称" />
            </p>
          </div>
          <div>
            <p>
              使用的试卷：
            </p>
            <p>
              <el-select v-model="addExam.e_pname" placeholder="请选择试卷">
                <el-option v-for="item in paperData" :key="item.paper_name" :label="item.paper_name" :value="item.paper_name" />
              </el-select>
            </p>
          </div>
          <div>
            <p>
              投放的班级
            </p>
            <p>
              <el-select v-model="addExam.e_cid" placeholder="请选择班级">
                <el-option v-for="item in classData" :key="item.c_name" :label="item.c_name" :value="item.c_id" />
              </el-select>
            </p>
          </div>
          <div>
            <p>
              考试开始时间
            </p>
            <p>
              <el-date-picker v-model="addExam.begin_time" type="datetime" placeholder="选择日期时间" />
            </p>
          </div>
          <div>
            <p>
              考试持续时间（分）
            </p>
            <p>
              <el-input v-model="addExam.e_duration" onkeyup="this.value=this.value.replace(/[^\d.]/g,'');" class="input-width" maxlength="4" placeholder="请输入整数" />
            </p>
          </div>
        </el-col>
        <el-col :span="12">
          <div>
            <p>
              是否单题显示
            </p>
            <p>
              <el-radio-group v-model="addExam.DTXS">
                <el-radio-button :label="true">单题</el-radio-button>
                <el-radio-button :label="false">整卷</el-radio-button>
              </el-radio-group>
            </p>
          </div>
          <div>
            <p>
              是否打乱题目
            </p>
            <p>
              <el-radio-group v-model="addExam.DLTM">
                <el-radio-button :label="true">打乱</el-radio-button>
                <el-radio-button :label="false">不打乱</el-radio-button>
              </el-radio-group>
            </p>
          </div>
          <div>
            <p>
              答题时不允许后退
            </p>
            <p>
              <el-radio-group v-model="addExam.BXHT">
                <el-radio-button :label="true">允许后退</el-radio-button>
                <el-radio-button :label="false">不允许</el-radio-button>
              </el-radio-group>
            </p>
          </div>
        </el-col>
      </el-row>

      <p>
        <el-button type="primary" @click="onUploadExam">新增</el-button>
      </p>
    </div>

    <!-- 删除考试 dialog -->
    <el-dialog title="警告" :visible.sync="deleteExamDialogVisible" width="30%">
      <span>确定永久删除该考试吗？</span>
      <span slot="footer" class="dialog-footer">
        <el-button @click="deleteExamDialogVisible = false">取 消</el-button>
        <el-button type="danger" @click="onDeleteExamRow">确 定</el-button>
      </span>
    </el-dialog>

    <!-- 查看考试详情 dialog -->
    <el-dialog title="考试详情" :visible.sync="GetRowInfoDialogVisible" width="50%">
      <el-row>
        <el-col v-for="(val, key) in rowData" :key="key" style="margin:0 0 10px 0;" :span="24">
          <span>{{ key }}：</span>
          <span style="color:#eb3941;">{{ val }}</span>
        </el-col>
      </el-row>
    </el-dialog>

  </div>
</template>

<script>
import { getPaper } from '@/api/paper'
import { getClass } from '@/api/class'
import { insert as examInsert, select as examSelect, examDelete } from '@/api/exam'
import { mapGetters } from 'vuex'

export default {
  name: 'TchTest',
  data() {
    return {
      isLoading: false, // 页面正在加载
      pageIndex: 0, // 页面索引
      rowData: {}, // 考试详情
      deleteExamDialogVisible: false, // 删除考试确认框
      GetRowInfoDialogVisible: false, // 查看考试详情
      deleteEid: -1, // 要删除的e_id
      homePage: {
        tabsActiveName: '0',
        serverTimeNow: '',
        tableHead: [
          { prop: 'c_name', label: '班级', width: '' },
          { prop: 'e_name', label: '考试名称', width: '' },
          { prop: 'e_duration', label: '考试时间(分)', width: '120' },
          { prop: 'begin_time', label: '开始时间', width: '' }
        ],
        haveBegunTableData: [],
        isOverTableData: [],
        notStartTableData: []
      }, // 首页数据
      paperData: [], // 试卷数据
      classData: [], // 班级数据
      addExam: {
        e_pname: '', // 关联的试卷
        e_pauthor: '', // 关联的试卷的作者
        e_author: '', // 该考试的创建者
        e_cid: '', // 关联的班级
        e_name: '', // 考试名称
        begin_time: '', // 考试开始时间
        e_duration: '', // 考试持续时间
        DTXS: false, // 单题显示
        DLTM: false, // 打乱题目
        BXHT: false// 不许后退
      }// 添加考试
    }
  },
  computed: {
    ...mapGetters(['name', 'avatar', 'roles'])
  },
  created: function() {
    this.onGetPaper()
  },
  methods: {
    onGetRowInfo(row) {
      this.rowData = row
      this.GetRowInfoDialogVisible = true
    },

    /**
     * @description: api调用，获取试卷列表，获取班级列表
     * @param {*}
     * @return {*}
     */
    async onGetPaper() {
      try {
        this.isLoading = true
        const callback = await getPaper()
        // this.isLoading = false
        this.paperData = []
        for (let i = 0; i < callback.data.length; i++) {
          if (callback.data[i]['paper_author'] === this.name) this.paperData.push(callback.data[i])
        }
        this.addExam.e_pauthor = this.name
        this.addExam.e_author = this.name
        // console.log(callback.data)
        this.onGetClass()
      } catch {
        this.isLoading = false
        return
      }
    },
    async onGetClass() {
      try {
        // console.log('ok')
        this.isLoading = true
        const callback = await getClass()
        this.classData = []
        for (let i = 0; i < callback.data.length; i++) {
          if (callback.data[i]['admin'] === this.name) this.classData.push(callback.data[i])
        }
        this.onGetExamList()
        // console.log(callback.data)
      } catch {
        this.isLoading = false
        return
      }
    },

    /**
     * 下载考试列表
     */
    async onGetExamList() {
      const data = {
        e_author: this.name
      }
      const callback = await examSelect(data)
      const tempMap = {}// 一个对象用来储存，减少查询次数
      this.homePage.serverTimeNow = callback.data.serverTimeNow

      this.homePage.haveBegunTableData = callback.data.haveBegunTableData
      for (let i = 0; i < this.homePage.haveBegunTableData.length; i++) {
        if (typeof (tempMap[this.homePage.haveBegunTableData[i].e_cid]) !== 'undefined') {
          this.homePage.haveBegunTableData[i].c_name = tempMap[this.homePage.haveBegunTableData[i].e_cid]
          console.log('wow省力了，')
          continue
        }
        for (let j = 0; j < this.classData.length; j++) {
          if (this.homePage.haveBegunTableData[i].e_cid === this.classData[j].c_id) {
            this.homePage.haveBegunTableData[i].c_name = this.classData[j].c_name
            tempMap[this.homePage.haveBegunTableData[i].e_cid] = this.classData[j].c_name
          }
        }
      }
      this.homePage.isOverTableData = callback.data.isOverTableData
      for (let i = 0; i < this.homePage.isOverTableData.length; i++) {
        if (typeof (tempMap[this.homePage.isOverTableData[i].e_cid]) !== 'undefined') {
          this.homePage.isOverTableData[i].c_name = tempMap[this.homePage.isOverTableData[i].e_cid]
          console.log('wow省力了，')
          continue
        }
        for (let j = 0; j < this.classData.length; j++) {
          if (this.homePage.isOverTableData[i].e_cid === this.classData[j].c_id) {
            console.log('isOverTableData找到了')
            this.homePage.isOverTableData[i].c_name = this.classData[j].c_name
            tempMap[this.homePage.isOverTableData[i].e_cid] = this.classData[j].c_name
          }
        }
      }
      this.homePage.notStartTableData = callback.data.notStartTableData
      for (let i = 0; i < this.homePage.notStartTableData.length; i++) {
        if (typeof (tempMap[this.homePage.notStartTableData[i].e_cid]) !== 'undefined') {
          this.homePage.notStartTableData[i].c_name = tempMap[this.homePage.notStartTableData[i].e_cid]
          console.log('wow省力了，')
          continue
        }
        console.log('循环', i)
        for (let j = 0; j < this.classData.length; j++) {
          console.log('循环j', j)
          if (this.homePage.notStartTableData[i].e_cid === this.classData[j].c_id) {
            console.log('notStartTableData找到了')
            this.homePage.notStartTableData[i].c_name = this.classData[j].c_name
            tempMap[this.homePage.notStartTableData[i].e_cid] = this.classData[j].c_name
          }
        }
      }
      console.log('tempMap是', tempMap)
      console.log('————————完成页面初始化————————')
      this.isLoading = false
    },
    /**
     * 删除一个考试前，弹出弹框
     */
    beforeDeleteExamRow(row) {
      this.deleteEid = row.e_id
      this.deleteExamDialogVisible = true
    },
    /**
     * 删除某一个考试
     */
    async onDeleteExamRow() {
      this.isLoading = true
      const data = {
        e_id: this.deleteEid
      }

      const callback = await examDelete(data)
      this.$message({
        message: callback.data.message,
        type: callback.data.type
      })
      this.isLoading = false
      this.deleteExamDialogVisible = false
      this.onGetPaper()
    },
    /**
     * 上传考试
     */
    async onUploadExam() {
      try {
        this.isLoading = true
        for (const item in this.addExam) {
          if (this.addExam[item] === '') {
            this.$message({
              message: `输入不完整！(${item}为空）`,
              type: 'warning'
            })
            this.isLoading = false
            return
          }
        }
        const callback = await examInsert(this.addExam)
        this.$message({
          message: callback.data.message,
          type: callback.data.type
        })

        this.pageIndex = 0
        this.onGetExamList()
      } catch (e) {
        console.log(e.message)
        this.isLoading = false
      }
    },

    /**
     * @description: 打开添加新考试页面
     * @param {*}
     * @return {*}
     */
    goToAddExamPage() {
      this.pageIndex = '新增考试'
    },
    /**
     * 返回到起始页
     */
    goBack() {
      this.pageIndex = 0
    },
    /**
    * 给table每格rows加上row_index属性
    */
    tableRowClassName({ row, rowIndex }) {
      row.row_index = rowIndex
    },
    /**
     * 点击了某一行
     */
    onRowClick(row) {
      console.log(row.row_index)
    },
    /**
     * @description:
     * @param {*}
     * @return {*}
     */
    reloadPage() {
      this.$router.go(0)
    }
  }
}
</script>

<style scoped>
.input-width {
  width: 220px;
}
.wrapper {
  background-color: #e6e6e6;
  padding: 10px;
  min-height: calc(100vh - 84px);
}
.card {
  background-color: #fff;
  padding: 24px;
  margin-bottom: 10px;
}
.narrow-card {
  background-color: #fff;
  padding: 24px;
  margin: 0 auto 60px auto;
  max-width: 980px;
}
.flex-row {
  display: flex;
  flex-direction: row;
  flex-wrap: wrap;
  align-items: center;
}
</style>
